package usersBodyService

import (
	"fmt"
	"gin/dao/entity"
	"gin/dao/mapper/users/usersBody"
	"gin/model"
	"gin/model/body"
	"gin/model/http_error"
	"strconv"
	"time"
)

// Add 添加数据
func Add(uid int64, p body.UsersBodyParam) {
	if p.Height == 0 || p.Weight == 0 {
		http_error.CustomPanic("数值填写不规范")
	}

	recordData := time.Now().Format("2006-01-02")

	param := entity.UsersBody{
		Uid:        uid,
		Height:     p.Height,
		Weight:     p.Weight,
		Bmi:        p.Bmi,
		BodyFat:    p.BodyFat,
		RecordDate: recordData,
	}

	info := usersBody.GetInfo(uid, recordData)
	if info.Id != 0 {
		usersBody.Update(param, info.Id)
	} else {
		usersBody.Add(param)
	}

}

// GetInfo 获取最新数据
func GetInfo(uid int64) entity.UsersBody {
	return usersBody.GetNew(uid)
}

// GetChartList 获取列表数据
func GetChartList(p body.UsersBodySelect) ([]string, []float64) {
	list := usersBody.ChartList(p)
	bodyMap := map[string]float64{}

	xAxis := make([]string, 0)
	yAxis := make([]float64, 0)
	switch p.DateType {
	case 1:
		for _, v := range list {
			bodyMap[getWeek(v.RecordDate)] = v.RecordData
		}
		xAxis = []string{"一", "二", "三", "四", "五", "六", "日"}
		for _, v := range xAxis {
			yAxis = append(yAxis, bodyMap[v])
		}
	case 2:
		for _, v := range list {
			bodyMap[getDay(v.RecordDate)] = v.RecordData
		}
		for i := 1; i <= monthDay(p.BeginTime); i++ {
			xAxis = append(xAxis, strconv.Itoa(i))
			yAxis = append(yAxis, bodyMap[strconv.Itoa(i)])
		}
	case 3:
		for _, v := range list {
			bodyMap[v.RecordDate] = v.RecordData
		}
		xAxis = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}
		for _, v := range xAxis {
			yAxis = append(yAxis, bodyMap[v])

		}
	}

	return xAxis, yAxis
}

func getWeek(date string) string {
	// 解析时间字符串为time.Time类型
	t, err := time.Parse("2006-01-02", date)
	if err != nil {
		fmt.Println("解析时间字符串失败:", err)
		return ""
	}
	// 获取星期几
	weekday := t.Weekday()

	switch weekday {
	case 1:
		return "一"
	case 2:
		return "二"
	case 3:
		return "三"
	case 4:
		return "四"
	case 5:
		return "五"
	case 6:
		return "六"
	case 7:
		return "日"
	}
	return ""
}

func getDay(date string) string {
	t, err := time.Parse("2006-01-02", date)
	if err != nil {
		fmt.Println("解析时间字符串失败:", err)
		return ""
	}
	day := t.Day()
	return strconv.Itoa(day)
}

func monthDay(date model.Time) int {
	// 解析时间字符串为time.Time类型
	t := time.Time(date)

	nextMonth := time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, t.Location())
	lastDayOfMonth := nextMonth.AddDate(0, 0, -1)
	// 获取指定月的天数
	daysInMonth := lastDayOfMonth.Day()
	return daysInMonth
}

// List 获取列表数据
func List(p body.UsersBodyList) ([]*entity.SimpleUsersBody, int64) {
	return usersBody.List(p)
}

// GetDetail 获取身体参数详情
func GetDetail(p body.UserBodyInfo) entity.DetailUsersBody {
	return usersBody.GetDetail(p)
}

// Del 删除对应用户身参数
func Del(p body.UserBodyInfo) {
	usersBody.Del(p)
}
